package com.example.task01_servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "ThreadServlet",urlPatterns="/thread")
public class ThreadServlet extends HttpServlet {
    private String name; //准备一个成员变量 作为共享资源
    //也可以不用上锁 去掉成员变量 我们用局部变量
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        synchronized (this) {
            //1.获取request对象中名字为name的参数数值并赋值给成员变量name
            name = request.getParameter("name");
            System.out.println("获取到的name数值为:"+name);
            //2.睡眠5s
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //3.使用打印流将成员变量name的数值发送给浏览器
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("<h1>"+name+"</h1>");
        }
    }
}
